<template>
    <div class="box">
        <div class="left_box">
            <div>
                <el-autocomplete
                    v-model="state"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入组织名称"
                    :maxlength="20"
                    prefix-icon="el-icon-search"
                    @select="getList"
                ></el-autocomplete>
            </div>
            <div class="tree">
                <el-tree
                    :data="data"
                    node-key="id"
                    draggable
                    icon-class="el-icon-arrow-right"
                    highlight-current="true"
                    :default-expanded-keys="expandedKeys"
                    @node-click="handleNodeClick"
                    @node-drop="handleDrop"
                >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <i :class="[data.icon]"></i>
                        <span :id="[data.id]" :style="{ color: data.isMatch == 1 ? '#004FAB' : '#333' }">{{ node.label }}</span>
                        <img v-if="data.deptFlag" class="isDivision" src="../../assets/img/icon.png" alt="">
                    </span>
                </el-tree>
            </div>
        </div>
        <div class="right_box">
            <div class="title">
                <p v-if="!form.name">添加组织</p>
                <p v-else>组织详情</p>
            </div>
            <div class="input_box">
                <div class="iputBox">
                    <el-form ref="rightForm" :rules="rules" :model="form">
                        <el-form-item prop="name">
                            <el-input v-model.trim="form.name" :maxlength="20" placeholder="请输入内容" @focus="ischang = true"></el-input>
                        </el-form-item>
                    </el-form>
                    <span v-if="isEdit&&ischang" @click="addConfirm">保存</span>
                </div>
                <el-switch v-model="form.deptFlag" @change="switchChange" active-text="是否设为事业部"></el-switch>
            </div>
            <div class="btn_box">
                <div class="btn confirm" v-if="!isEdit" @click="addOrg">保存</div>
                <div class="btn delete" v-if="isEdit" @click="deleteproject">删除</div>
            </div>
        </div>
        <!-- <el-dialog title="编辑组织名" :visible.sync="addVisible" width="590px" top="40vh">
            <el-form class="newForm" ref="form" :rules="rules" :model="form" label-position="left" label-width="0">
                <el-form-item style="margin-left:0;" prop="name">
                    <el-input placeholder="请输入组织名称" class="newFormInput" v-model="form.name" :maxlength="20"></el-input>
                </el-form-item>
            </el-form>
            <div class="tableBtnBox">
                <button class="btn1" @click="cancelAdd">取消</button>
                <button class="btn2" @click="addConfirm">确认</button>
            </div>
        </el-dialog> -->
        <!-- 删除弹窗 -->
        <myDialog
            :isShow="delVisible"
            title="删除组织"
            :context="`是否删除【${form.name}】？`"
            @cancel="delVisible = false"
            @confirm="confirmDel"
        ></myDialog>
        <!-- 移动组织弹窗 -->
        <myDialog
            :isShow="removeVisible"
            title="删除组织"
            context="是否将该组织及下属组织移动到此处？"
            @cancel="concelRemove"
            @confirm="confirmRemove"
        ></myDialog>
    </div>
</template>
<script>
import { throttle } from '@/utils/tools.js';
import {
    organizationList,
    organizationAdd,
    organizationDelete,
    organizationEdit,
    organizationUpdate,
    getOrganizationListLikeName
} from '@/api/index.js';
import myDialog from '../components/dialog.vue';
export default {
    components: {
        myDialog
    },
    data() {
        return {
            state: '',
            timeout: null,
            form: {
                name: '',
                deptFlag: false
            },
            rules: {
                name: [{ required: true, message: '请输入组织名称', trigger: 'change' }]
            },
            input: '',
            addVisible: false,
            data: [],
            isEdit: false,// 是否点击节点查看详情
            ischang: false, // 点击节点是否编辑
            parentId: undefined, // 点击组织的父级id
            selfId: undefined, // 点击节点自身的id
            expandedKeys: [], // 默认展开
            delVisible: false, // 删除弹窗
            removeVisible: false, // 移动节点
            nodeObj: {}, // node节点信息
            restaurants: []
        };
    },
    mounted() {
        this.getList();
    },
    methods: {
        search: throttle(function() {
            this.expandedKeys = [];
            this.getList();
        }, 3000),
        querySearchAsync(queryString, cb) {
            console.log(queryString, cb);
            getOrganizationListLikeName({ name: this.state }).then(res => {
                if (res.code === 200) {
                    let list = res.result.map(n => {
                        return {
                            value: n.organizationName
                        };
                    });
                    console.log(list);
                    cb(list);
                }
            });
        },
        // 获取树形列表
        getList() {
            let that = this;
            let params = {};
            if (this.state) params.name = this.state;
            organizationList(params).then(res => {
                if (res.result && res.result.length > 0) {
                    let list = res.result;
                    const newChild = { id: 'add', label: '添加组织', parentId: '0', icon: 'el-icon-circle-plus', children: [] };
                    list.push(newChild);
                    // 递归添加 （添加组织数据）
                    let forObj = list => {
                        list.forEach(row => {
                            if (row.id != 'add') {
                                const newChild = {
                                    id: 'add',
                                    label: '添加组织',
                                    parentId: row.id,
                                    icon: 'el-icon-circle-plus',
                                    children: []
                                };
                                row.children = row.children ? row.children : [];
                                row.children.push(newChild);
                                forObj(row.children);
                                if (row.isMatch) that.expandedKeys.push(row.id);
                            }
                        });
                    };
                    forObj(list);
                    this.data = list;
                    console.log('expandedKeys', that.expandedKeys);
                }
            });
        },
        // 添加组织
        addOrg() {
            let that = this;
            console.log(this.$refs['rightForm']);
            this.$refs['rightForm'].validate(valid => {
                if (valid) {
                    let params = {
                        name: this.form.name,
                        deptFlag: this.form.deptFlag?1:0,
                        id: this.parentId ? this.parentId : 0
                    };
                    organizationAdd(params).then(res => {
                        if (res.code === 200) {
                            that.$message.success('添加成功');
                            that.getList();
                        } else that.$message.error(res.message);
                    });
                } else return false;
            });
        },
        handleNodeClick(data) {
            if (data.id == 'add') {
                if (this.$refs['rightForm']) {
                    this.$refs['rightForm'].resetFields();
                }
                this.isEdit = false;
            } else {
                this.form.name = data.label;
                this.form.deptFlag = data.deptFlag?true:false;
                this.isEdit = true;
            }
            this.ischang = false
            this.parentId = data.parentId;
            this.selfId = data.id;
            console.log(data);
            if (!data.children) return;
            let item = data.children.find(item => {
                return item.id == 'add';
            });
        },
        // 拖拽成功时触发
        handleDrop(before, after, inne, event) {
            console.log(before, after, inne, event);
            this.removeVisible = true;
            this.nodeObj = {
                before,
                after,
                inne,
                event
            };
        },
        // 取消移动
        concelRemove() {
            this.removeVisible = false;
            this.getList();
        },
        // 确定移动
        confirmRemove() {
            const { before, after, inne, event } = this.nodeObj;
            let startInfo = before.data.id;
            let organizationId = after.data.parentId;
            let params = {
                targetId: organizationId,
                organizationId: startInfo
            };
            organizationUpdate(params).then(res => {
                // 不管有没有成功都刷新一下列表
                this.getList();
                if (res.code === 200) {
                    this.removeVisible = false;
                    this.$message.success('移动成功');
                } else this.$message.error(res.message);
            });
        },
        //取消新增
        cancelAdd() {
            this.form = {
                name: ''
            };
        },
        // 是否设为事业部
        switchChange () {
            let that = this
            if (this.isEdit) {
                // 编辑状态才进行操作
                let form = {
                        organizationId: that.selfId, //项目id
                        deptFlag: that.form.deptFlag?1:0
                    };
                    //项目类型
                    organizationEdit(form).then(res => {
                        if (res.code === 200) {
                            that.$message.success('编辑成功');
                            that.getList();
                        } else {
                            that.$message({
                                type: 'error',
                                message: res.message
                            });
                        }
                    });
            }
        },
        //编辑组织点击确认
        addConfirm: throttle(function() {
            let that = this;
            this.$refs['rightForm'].validate(valid => {
                if (valid) {
                    let form = {
                        organizationId: that.selfId, //项目id
                        name: that.form.name, //项目名称
                        deptFlag: that.form.deptFlag?1:0
                    };
                    //项目类型
                    organizationEdit(form).then(res => {
                        if (res.code === 200) {
                            that.$message.success('编辑成功');
                            that.getList();
                            that.isEdit = false
                            this.$refs['rightForm'].resetFields();//清空表单
                        } else {
                            that.$message({
                                type: 'error',
                                message: res.message
                            });
                        }
                    });
                } else return false;
            });
        }, 3000),
        //删除项目
        deleteproject() {
            this.delVisible = true;
        },
        // 确认删除
        confirmDel() {
            let that = this;
            organizationDelete({ organizationId: that.selfId }).then(res => {
                if (res.code == 200) {
                    that.$message.success('删除成功');
                    that.delVisible = false;
                    this.form.name = '';
                    that.getList();
                }
            });
        }
    }
};
</script>
<style scoped lang="scss">
.box {
    width: 100%;
    display: flex;
}
.left_box {
    width: 60%;
    height: calc(100vh - 11.25rem /* 180/16 */);
    background: #ffffff;
    box-shadow: 0px 11px 14px -10px #e5eced;
    border-radius: 5px;
    box-sizing: border-box;
    padding: 1.625rem /* 26/16 */ 1.875rem /* 30/16 */;
}
.right_box {
    width: 40%;
    height: calc(100vh - 11.25rem /* 180/16 */);
    background: #ffffff;
    box-shadow: 0px 11px 14px -10px #e5eced;
    border-radius: 5px;
    margin-left: 1.875rem /* 30/16 */;
    box-sizing: border-box;
    padding: 1.625rem /* 26/16 */ 1.875rem /* 30/16 */;
}
.tree {
    margin-top: 2.125rem /* 34/16 */;
    height: 80%;
    overflow-y: scroll;
}
.tree::-webkit-scrollbar {
    display: none;
}
.custom-tree-node{
    display: flex;
    align-items: center;
    font-family: PingFangSC-Regular, PingFang SC;
    .isDivision{
        width: 1.125rem /* 18/16 */;
        height: 1.125rem /* 18/16 */;
        margin-left: .625rem /* 10/16 */;
    }
}
.title {
    width: 100%;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 22px;
    display: flex;
}
.edit_box {
    margin-left: auto;
    cursor: pointer;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 22px;
}
.input_box {
    margin-top: 2.125rem /* 34/16 */;
    margin-bottom: 1.5rem /* 24/16 */;
    /deep/.el-input__inner {
        width: 11.8125rem /* 189/16 */;
    }
    .iputBox {
        display: flex;
        > span {
            color: #214A8F;
            font-size: 1rem /* 16/16 */;
            margin-left: 1.875rem /* 30/16 */;
            line-height: 2.1875rem /* 35/16 */;
            cursor: pointer;
        }
    }
}
.btn_box {
    width: 100%;
    display: flex;
    margin-top: 1.875rem /* 30/16 */;
}
.btn {
    width: 5.125rem /* 82/16 */;
    height: 2.1875rem /* 35/16 */;
    border-radius: 0.3125rem /* 5/16 */;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 2.1875rem /* 35/16 */;
    text-align: center;
    cursor: pointer;
}
.confirm {
    background: #214a8f;
    color: #ffffff;
}
.delete {
    color: #ffffff;
    background: #d0021b;
}
.newForm {
    .el-form-item {
        border-bottom: 1px solid #d8d8d8;
    }
}
.el-dialog__header {
    background: rgba(33, 74, 143, 0.1);
    font-size: 18px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(33, 74, 143, 1);
}
.el-dialog__body {
    max-height: 720px;
    // overflow-y: scroll;
    position: relative;
}
.el-icon-close:before {
    border-radius: 50%;
    color: #fff;
    background-color: rgba(33, 74, 143, 1);
}
.newForm/deep/.el-input__inner {
    border: none;
}
.specityBox {
    .tableBox {
        max-height: 452px;
        overflow-y: scroll;
    }
    .tableBox::-webkit-scrollbar {
        width: 0;
    }
}
.el-dialog__body {
    padding: 2.5rem /* 40/16 */ 0 1.25rem /* 20/16 */ 1.25rem /* 20/16 */ !important;
    padding-top: 2.5rem /* 40/16 */ !important;
    padding-bottom: 64px;
}
.tableBtnBox {
    margin-top: 1.875rem /* 30/16 */;
    text-align: center;
    .btn1 {
        width: 90px;
        height: 35px;
        background: rgba(0, 79, 171, 0.2);
        border-radius: 5px;
        border: none;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 79, 171, 1);
        margin-right: 56px;
    }
    .btn2 {
        width: 90px;
        height: 35px;
        background: rgba(0, 79, 171, 1);
        border-radius: 5px;
        border: none;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
    }
}
.el-form-item__content {
    margin-left: 0 !important;
}
.newObjectConfirm {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
    line-height: 28px;
    background: rgba(0, 79, 171, 1) !important;
}
.newObjectCancel {
    width: 90px !important;
    height: 35px;
    background: rgba(255, 255, 255, 0.2) !important;
    border-radius: 5px;
}
.tree .el-tree-node__expand-icon {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
    display: none;
}
.el-icon-caret-right:before {
    content: '\e6e0' !important;
    font-size: 18px;
}
.tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
    content: '\e6df';
    font-size: 18px;
}
.el-icon-circle-plus {
    color: #214a8f;
    margin-left: -16px;
}
#add {
    color: #214a8f;
}
</style>
